package com.example.shop_car_2208.net

import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 网络工具类
 */
class RetrofitUtils {
    //伴生对象------静态单利
    companion object{
        //获取retrofit对象
        fun getRetrofit():Retrofit{
            val okHttpclient = OkHttpClient.Builder()
                .readTimeout(5,TimeUnit.SECONDS)//读超时
                .connectTimeout(5,TimeUnit.SECONDS)//连接超时
                .writeTimeout(5,TimeUnit.SECONDS)//写超时时长
                //日志拦截器
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                //自定义拦截器----请求头token
                .addInterceptor{
                    val token = SPUtils.getInstance().getString(Const.SP_TOKEN)
                    val request = it.request().newBuilder().addHeader("token",token).build()
                    it.proceed(request)
                }
                .build()
            return Retrofit.Builder()
                .client(okHttpclient)
                .baseUrl(Const.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//后续写协程，不用添加
                .build()


        }
    }
}